package com.yamaha.bikedesalon;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.FacebookException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.widget.WebDialog;
import com.facebook.widget.WebDialog.OnCompleteListener;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.sromku.simple.fb.SimpleFacebook;
import com.yamaha.bikedesalon.util.API;
import com.yamaha.bikedesalon.util.SCStaticFunc;

public class AddEditFormFragment extends AMyActivity
		implements
			OnItemClickListener {

	private final String TAG = this.getClass().getSimpleName();
	private final List<String> imagesList = new ArrayList<String>();
	private final MyAdapter adapter = new MyAdapter();
	private final static int TAKE_A_PHOTO = 50202;
	private final static int SELECT_PICTURE = 50230;
	private final static int REQUEST_CODE_CROP = 50240;
	public static final int MEDIA_TYPE_IMAGE = 1;
	private final Map<String, Bitmap> bitmaps = new HashMap<String, Bitmap>();
	private int userChooseImageIndex;
	private MyState state = MyState.NONE;
	private JSONObject detail;

	private enum MyState {
		PHOTO, NONE
	}

	public AddEditFormFragment() {
		super(MenuType.NONE);
	}

	@Override
	protected List<EditText> getEditTexts() {
		final ArrayList<EditText> list = new ArrayList<EditText>();

		final EditText title = (EditText) findViewById(R.id.add_edit_title);
		final EditText price = (EditText) findViewById(R.id.add_edit_price);

		list.add(title);
		list.add(price);

		return list;
	}

	@Override
	public void onMyClick(View v) {
		switch (v.getId()) {
			case R.id.add_edit_brand_bg : {
				doShowBrand();
			}
				break;
			case R.id.add_edit_category_bg : {
				doShowCategory();
			}
				break;
			case R.id.add_edit_model_bg : {
				doShowModel();
			}
				break;
			case R.id.add_edit_province_bg : {
				doShowProvince();
			}
				break;
			case R.id.add_edit_save_bt : {
				doSave();
			}
				break;
			case R.id.add_edit_check_box : {
				doCheckFB();
			}
				break;
		}
	}

	private void doCheckFB() {
		final ImageView checkbox = (ImageView) findViewById(R.id.add_edit_check_box);
		if (checkbox.getTag() == null) {
			checkbox.setImageDrawable(getResources().getDrawable(R.drawable.add_edit_check_box_checked));
			checkbox.setTag(new Object());
		} else {
			checkbox.setImageDrawable(getResources().getDrawable(R.drawable.add_edit_check_box_uncheck));
			checkbox.setTag(null);
		}
	}

	@Override
	protected int getLayoutId() {
		return R.layout.add_edit_form_page;
	}

	@Override
	protected void onMyCreated(Bundle savedInstanceState) {
		final RelativeLayout brandButton = (RelativeLayout) findViewById(R.id.add_edit_brand_bg);
		final RelativeLayout categoryButton = (RelativeLayout) findViewById(R.id.add_edit_category_bg);
		final RelativeLayout modelButton = (RelativeLayout) findViewById(R.id.add_edit_model_bg);
		final RelativeLayout provinceButton = (RelativeLayout) findViewById(R.id.add_edit_province_bg);
		final ImageView checkbox = (ImageView) findViewById(R.id.add_edit_check_box);
		final ImageButton saveButton = (ImageButton) findViewById(R.id.add_edit_save_bt);
		final Gallery gallery = (Gallery) findViewById(R.id.add_edit_image_gallery);

		gallery.setAdapter(adapter);
		gallery.setOnItemClickListener(this);
		brandButton.setOnClickListener(this);
		categoryButton.setOnClickListener(this);
		provinceButton.setOnClickListener(this);
		modelButton.setOnClickListener(this);
		saveButton.setOnClickListener(this);
		checkbox.setOnClickListener(this);

		deleteMyFile();

		final String temp = getIntent().getStringExtra("detail");
		if (null == temp) {
			// finish();
		} else {
			try {
				LogUtil.d(TAG, temp);
				detail = new JSONObject(temp);

				final EditText detailText = (EditText) findViewById(R.id.add_edit_detail);
				final EditText title = (EditText) findViewById(R.id.add_edit_title);
				final EditText price = (EditText) findViewById(R.id.add_edit_price);

				title.setText(detail.getString("title"));
				detailText.setText(detail.getString("description"));
				price.setText(detail.getString("price").replaceAll(",", ""));

				final JSONArray list = (JSONArray) SCStaticFunc.getData(this, SCStaticFunc.BAND);

				{
					final TextView brandTextView = (TextView) findViewById(R.id.add_edit_brand_spinner);
					brandTextView.setText(detail.getString("brand_name"));
					brandButton.setTag(detail.getString("brand_id"));
				}

				{
					final RelativeLayout modelLL = (RelativeLayout) findViewById(R.id.add_edit_model_bg);
					modelLL.setTag(detail.getString("model_id"));

					final TextView modelTextView = (TextView) findViewById(R.id.add_edit_model_spinner);
					modelTextView.setText(detail.getString("model_name"));
				}

				{
					final RelativeLayout categoryLL = (RelativeLayout) findViewById(R.id.add_edit_category_bg);
					categoryLL.setTag(detail.getString("category_id"));

					final TextView modelTextView = (TextView) findViewById(R.id.add_edit_category_spinner);
					modelTextView.setText(detail.getString("category_name"));
				}

				{
					final RelativeLayout button = (RelativeLayout) findViewById(R.id.add_edit_province_bg);
					button.setTag(detail.getString("province_id"));

					final TextView modelTextView = (TextView) findViewById(R.id.add_edit_province_spinner);
					modelTextView.setText(detail.getString("province_name"));
				}

				final JSONArray array = detail.getJSONArray("image");
				imagesList.clear();
				if (null != array && array.length() > 0) {
					for (int i = 0; i < array.length(); i++) {
						imagesList.add(array.getString(i));
					}
				}

			} catch (JSONException e) {
				LogUtil.e(TAG, e.getMessage(), e);
			}
		}
	}
	private boolean validate() {
		final RelativeLayout brandButton = (RelativeLayout) findViewById(R.id.add_edit_brand_bg);
		final RelativeLayout categoryButton = (RelativeLayout) findViewById(R.id.add_edit_category_bg);
		final RelativeLayout modelButton = (RelativeLayout) findViewById(R.id.add_edit_model_bg);
		final RelativeLayout provinceButton = (RelativeLayout) findViewById(R.id.add_edit_province_bg);
		final EditText detail = (EditText) findViewById(R.id.add_edit_detail);
		final EditText title = (EditText) findViewById(R.id.add_edit_title);

		if (brandButton.getTag() == null) {
			Utils.showToast(this, "Please select Brand");
			return false;
		}

		if (categoryButton.getTag() == null) {
			Utils.showToast(this, "Please select Category");
			return false;
		}

		if (modelButton.getTag() == null) {
			Utils.showToast(this, "Please select Model");
			return false;
		}

		if (provinceButton.getTag() == null) {
			Utils.showToast(this, "Please select Province");
			return false;
		}

		if (detail.getText().toString().length() == 0) {
			Utils.showToast(this, "Please input Detail");
			return false;
		}

		if (title.getText().toString().length() == 0) {
			Utils.showToast(this, "Please input Title");
			return false;
		}

		// Check Image
		boolean hasImage = false;
		for (int i = 0; i <= 4 && !hasImage; i++) {
			final Bitmap bitmap = loadFile("" + i);
			if (null != bitmap) {
				hasImage = true;
			}
		}

		if (!hasImage) {
			Utils.showToast(this, "Please insert at least one image.");
			return false;
		}

		return true;
	}

	private void doSave() {

		if (validate()) {

			final AsyncHttpClient client = new AsyncHttpClient();
			final RequestParams params = new RequestParams();

			final RelativeLayout brandButton = (RelativeLayout) findViewById(R.id.add_edit_brand_bg);
			final RelativeLayout categoryButton = (RelativeLayout) findViewById(R.id.add_edit_category_bg);
			final RelativeLayout modelButton = (RelativeLayout) findViewById(R.id.add_edit_model_bg);
			final RelativeLayout provinceButton = (RelativeLayout) findViewById(R.id.add_edit_province_bg);
			final EditText detail = (EditText) findViewById(R.id.add_edit_detail);
			final EditText title = (EditText) findViewById(R.id.add_edit_title);

			// Check Image
			boolean hasImage = false;
			for (int i = 0; i <= 4 && !hasImage; i++) {
				final Bitmap bitmap = loadFile("" + i);
				if (null != bitmap) {
					hasImage = true;
				}
			}

			if (null != this.detail) {
				try {
					String postId = this.detail.getString("post_id");
					params.put("postpart_id", postId);
				} catch (JSONException e) {
					LogUtil.e(TAG, e.getMessage(), e);
				}
			}

			final String brand = (null != brandButton.getTag())
					? brandButton.getTag().toString()
					: "";
			params.put("brand_id", brand);

			final String category = (null != categoryButton.getTag())
					? categoryButton.getTag().toString()
					: "";
			params.put("category_id", category);

			final String model = (null != modelButton.getTag())
					? modelButton.getTag().toString()
					: "";
			params.put("model_id", model);

			final String province = (null != provinceButton.getTag())
					? provinceButton.getTag().toString()
					: "";
			params.put("province_id", province);
			params.put("detail", detail.getText().toString());
			params.put("title", title.getText().toString());
			params.put("user_id", SCStaticFunc.getUserId(this));

			int index = 0;
			for (int i = 0; i < 5; i++) {
				try {
					final Bitmap bitmap = loadFile("" + i);

					if (null != bitmap) {
						final ByteArrayOutputStream baos = new ByteArrayOutputStream();
						bitmap.compress(CompressFormat.JPEG, 85, baos);
						params.put("image_" + i, new ByteArrayInputStream(baos.toByteArray()), ("image_" + index + ".jpg"), "image/jpg");
					}
				} catch (Exception e) {
					LogUtil.e(TAG, e.getMessage(), e);
				}
			}

			final ProgressDialog dialog = Utils.showProgressDialog(this, "", "Saving...");

			LogUtil.v(TAG, "Params : " + params.toString());
			client.post(API.NEW_POST, params, new MyAsyncHttpResponseHandler(API.NEW_POST, this) {

				@Override
				protected void onAsyncSuccess(final Object res)
						throws JSONException {
					final String message = (String) res;

					Utils.showToast(AddEditFormFragment.this, message);

					final ImageView checkbox = (ImageView) findViewById(R.id.add_edit_check_box);
					if (checkbox.getTag() != null) {

						final String picture = "http://ysf.flexintelligent.com/assets/images/pp.jpg";

						final Bundle params = new Bundle();
						params.putString("name", getResources().getString(R.string.app_name));
						params.putString("caption", title.getText().toString());
						params.putString("description", detail.getText().toString());
						params.putString("link", "");
						params.putString("picture", picture);

						LogUtil.v(TAG, "Share Param : " + params.toString());

						final WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(AddEditFormFragment.this, SimpleFacebook.getOpenSession(), params)).setOnCompleteListener(new OnCompleteListener() {

							@Override
							public void onComplete(final Bundle values, final FacebookException error) {
								if (error == null) {
									// When the story is posted, echo the
									// success
									// and the post Id.
									final String postId = values.getString("post_id");
									if (postId != null) {
										LogUtil.i(TAG, "Post Success : " + postId);
										Utils.showToast(AddEditFormFragment.this, "Post Success");

										finish();
										overridePendingTransition(0, 0);

									} else {
										// User clicked the Cancel button
										LogUtil.i(TAG, "User click Cancel.");
										Utils.showToast(AddEditFormFragment.this, "Publish cancelled");

										finish();
										overridePendingTransition(0, 0);
									}
								} else if (error instanceof FacebookOperationCanceledException) {
									// User clicked the "x" button
									LogUtil.i(TAG, "User click Cancel.");
									Utils.showToast(AddEditFormFragment.this, "Publish cancelled");

									finish();
									overridePendingTransition(0, 0);
								} else {
									// Generic, ex: network error
									LogUtil.e(TAG, "Facebook Share Error : " + error.getMessage(), error);
									Utils.showToast(AddEditFormFragment.this, error.getMessage());

									finish();
									overridePendingTransition(0, 0);
								}
							}

						}).build();
						feedDialog.show();
					} else {
						finish();
						overridePendingTransition(0, 0);
					}
				}

				@Override
				public void onFinish() {
					super.onFinish();
					dialog.dismiss();
				}
			});
		}
	}

	private void doShowModel() {
		try {
			final JSONArray list = (JSONArray) SCStaticFunc.getData(this, SCStaticFunc.MODEL);

			final LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
			for (int i = 0; i < list.length(); i++) {
				final JSONObject obj = list.getJSONObject(i);
				map.put(obj.getString("name"), obj.getString("model_id"));
			}

			final String[] items = map.keySet().toArray(new String[map.keySet().size()]);

			final AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Model");
			builder.setItems(items, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {

					final RelativeLayout modelButton = (RelativeLayout) findViewById(R.id.add_edit_model_bg);
					final String modelId = map.get(items[which]);
					modelButton.setTag(modelId);

					final TextView modelTextView = (TextView) findViewById(R.id.add_edit_model_spinner);
					modelTextView.setText(items[which]);

				}
			});
			builder.create().show();
		} catch (JSONException e) {
			LogUtil.e(this, TAG, e.getMessage(), e);
		}
	}

	private void doShowBrand() {
		try {
			final JSONArray list = (JSONArray) SCStaticFunc.getData(this, SCStaticFunc.BAND);

			final LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
			for (int i = 0; i < list.length(); i++) {
				final JSONObject obj = list.getJSONObject(i);
				map.put(obj.getString("name"), obj.getString("brand_id"));
			}

			final String[] items = map.keySet().toArray(new String[map.keySet().size()]);

			final AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Brand");
			builder.setItems(items, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {

					final RelativeLayout modelButton = (RelativeLayout) findViewById(R.id.add_edit_brand_bg);
					final String modelId = map.get(items[which]);
					modelButton.setTag(modelId);

					final TextView modelTextView = (TextView) findViewById(R.id.add_edit_brand_spinner);
					modelTextView.setText(items[which]);

				}
			});
			builder.create().show();
		} catch (JSONException e) {
			LogUtil.e(this, TAG, e.getMessage(), e);
		}
	}

	private void doShowCategory() {
		try {
			final JSONArray list = (JSONArray) SCStaticFunc.getData(this, SCStaticFunc.CATEGORY);

			final LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
			for (int i = 0; i < list.length(); i++) {
				final JSONObject obj = list.getJSONObject(i);
				map.put(obj.getString("name"), obj.getString("category_id"));
			}

			final String[] items = map.keySet().toArray(new String[map.keySet().size()]);

			final AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Category");
			builder.setItems(items, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {

					final RelativeLayout modelButton = (RelativeLayout) findViewById(R.id.add_edit_category_bg);
					final String modelId = map.get(items[which]);
					modelButton.setTag(modelId);

					final TextView modelTextView = (TextView) findViewById(R.id.add_edit_category_spinner);
					modelTextView.setText(items[which]);

				}
			});
			builder.create().show();
		} catch (JSONException e) {
			LogUtil.e(this, TAG, e.getMessage(), e);
		}
	}

	private void doShowProvince() {
		try {
			final JSONArray list = (JSONArray) SCStaticFunc.getData(this, SCStaticFunc.PROVINCE);

			final LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
			for (int i = 0; i < list.length(); i++) {
				final JSONObject obj = list.getJSONObject(i);
				map.put(obj.getString("name"), obj.getString("id"));
			}

			final String[] items = map.keySet().toArray(new String[map.keySet().size()]);

			final AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Dealer");
			builder.setItems(items, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {

					final RelativeLayout button = (RelativeLayout) findViewById(R.id.add_edit_province_bg);
					final String modelId = map.get(items[which]);
					button.setTag(modelId);

					final TextView modelTextView = (TextView) findViewById(R.id.add_edit_province_spinner);
					modelTextView.setText(items[which]);

				}
			});
			builder.create().show();
		} catch (JSONException e) {
			LogUtil.e(this, TAG, e.getMessage(), e);
		}
	}

	private class MyAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return 5;
		}

		@Override
		public Object getItem(int position) {
			return imagesList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			final ImageView imageView = new ImageView(AddEditFormFragment.this);
			imageView.setScaleType(ScaleType.FIT_CENTER);
			final Gallery.LayoutParams params = new Gallery.LayoutParams(500, 250);
			imageView.setLayoutParams(params);
			imageView.setPadding(25, 5, 25, 5);
			imageView.setTag(position);

			final Bitmap bitmap = loadFile("" + position);
			if (null != bitmap) {
				LogUtil.i(TAG, "User Image Index : " + position + " from Bitmap.");
				imageView.setImageBitmap(bitmap);
			} else {
				if (position < imagesList.size()) {

					final String url = imagesList.get(position);
					imageLoader.displayImage(url, imageView, new ImageLoadingListener() {

						@Override
						public void onLoadingStarted(String imageUri, View view) {
							LogUtil.i("BikeDetailFragment", "Load Image Started : " + imageUri);
						}

						@Override
						public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
							LogUtil.w("BikeDetailFragment", "Load Image Failed : " + imageUri);
						}

						@Override
						public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
							bitmaps.put(imageUri, loadedImage);
							imageView.setTag(imageUri);
							saveFile("" + position, loadedImage);
						}

						@Override
						public void onLoadingCancelled(String imageUri, View view) {
							// TODO Auto-generated method stub

						}
					});
				} else {
					imageView.setImageResource(R.drawable.plus_button);
				}
			}

			return imageView;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
		final ImageView imageButton = (ImageView) v;
		final int index = (Integer) imageButton.getTag();

		final String[] options = {"Camera", "Picture Library"};
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Choose...");
		builder.setItems(options, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(final DialogInterface dialog, int which) {
				switch (which) {
					case 0 : {
						handleCamera(index);
					}
						break;
					case 1 : {
						handleChooseImageFromLibrary(index);
					}
						break;
				}
				dialog.dismiss();
			}
		});
		builder.create().show();
	}

	private void handleChooseImageFromLibrary(final int index) {
		LogUtil.i("WantToSEllEditFragment", "User chooose image index : " + index);

		userChooseImageIndex = index;
		state = MyState.PHOTO;

		if (isIntentAvailable(this, MediaStore.ACTION_IMAGE_CAPTURE)) {
			final Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
			photoPickerIntent.setType("image/*");
			startActivityForResult(photoPickerIntent, SELECT_PICTURE);
		} else {
			LogUtil.w("WantToSellEditFragment", "User has NOT Gallery.");
		}
	}

	private void handleCamera(final int index) {

		if (isIntentAvailable(this, MediaStore.ACTION_IMAGE_CAPTURE)) {

			LogUtil.i("WantToSEllEditFragment", "User chooose image index : " + index);

			userChooseImageIndex = index;
			state = MyState.PHOTO;

			dispatchTakePictureIntent(TAKE_A_PHOTO);

		} else {
			LogUtil.w("WantToSellEditFragment", "User has NOT Camera.");
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == TAKE_A_PHOTO) {
			handleSmallCameraPhoto(data);
		} else if (requestCode == SELECT_PICTURE) {
			handleAfterChooseImageFromGallery(data);
		}

	}

	private void handleAfterChooseImageFromGallery(final Intent data) {
		try {
			final Uri selectedImage = data.getData();
			InputStream imageStream = getContentResolver().openInputStream(selectedImage);
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = 2;
			final Bitmap bitmap = BitmapFactory.decodeStream(imageStream, null, options);
			if (null != bitmap) {

				// final Uri uri = Uri.fromFile(file);
				// handleCrop(uri);
				if (bitmap != null) {
					saveFile("" + userChooseImageIndex, bitmap);
					adapter.notifyDataSetChanged();
				} else {
					Toast.makeText(this, "Cannot save picture, Please try again.", Toast.LENGTH_SHORT).show();
				}
			}

		} catch (FileNotFoundException e) {
			LogUtil.e(TAG, "handleAfterChooseImageFromGallery : " + e.getMessage(), e);
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
		}
	}

	private boolean saveFile(final String fileName, final Bitmap bitmap) {

		LogUtil.i("WantToSellEditFragment", "Save File : " + fileName);

		try {
			final FileOutputStream fileOutputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
			bitmap.compress(Bitmap.CompressFormat.JPEG, 95, fileOutputStream);

			return true;
		} catch (IOException e) {
			LogUtil.e("WantToSellEditFragment", "Save File : " + e.getMessage(), e);
		}

		return false;
	}

	private void deleteMyFile() {

		for (int i = 0; i <= 4; i++) {

			final String fileName = "" + i;
			LogUtil.i("WantToSellEditFragment", "Delete File : " + fileName);
			deleteFile("" + i);
		}
	}

	private void dispatchTakePictureIntent(int actionCode) {
		Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(this)));
		startActivityForResult(takePictureIntent, actionCode);
	}

	public static boolean isIntentAvailable(Context context, String action) {
		final PackageManager packageManager = context.getPackageManager();
		final Intent intent = new Intent(action);
		List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
		return list.size() > 0;
	}

	private File getTempFile(Context context) {
		final File path = new File(Environment.getExternalStorageDirectory(), context.getPackageName());
		if (!path.exists()) {
			path.mkdir();
		}
		return new File(path, "image.tmp");
	}

	private Bitmap loadFile(final String fileName) {

		try {
			FileInputStream fileInputStream = openFileInput(fileName);
			final Bitmap bitmap = BitmapFactory.decodeStream(fileInputStream);

			return bitmap;
		} catch (FileNotFoundException e) {
			LogUtil.w("WantToSellEditFragment", "Load File : " + e.getMessage() + " FileNotFoundException");
		}

		return null;
	}

	private void handleSmallCameraPhoto(Intent intent) {
		final File file = getTempFile(this);

		LogUtil.i("WantToSellEditFragment", "Back from Camera with Index : " + userChooseImageIndex);

		final Options options = new Options();
		options.inSampleSize = 2;
		final Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
		if (null != bitmap) {

			// final Uri uri = Uri.fromFile(file);
			// handleCrop(uri);
			if (bitmap != null) {
				saveFile("" + userChooseImageIndex, bitmap);
				adapter.notifyDataSetChanged();
			} else {
				Toast.makeText(this, "Cannot save picture, Please try again.", Toast.LENGTH_SHORT).show();
			}
		}
	}

}
